﻿// owner 蒋家伟

#include "Task.h"

// jsdk
#include "ITaskDescription.h"
#include "ITaskExectutable.h"
#include "Dbg_Warn_Define.h"
#include "TaskManager.h"
#include "TaskEvent.h"
#include "TaskEventArgs.h"
#include "StringUtils.h"

using namespace jsdk;

OwnerPtr<ITask> jsdk::Task::create(OwnerPtr<ITaskDescription> opTaskDescription, uint32_t delayTime)
{
    return NEW_AS_OWNERPTR(Task, std::move(opTaskDescription), delayTime);
}

const ITaskDescription * jsdk::Task::getTaskDescription() const
{
    return m_opTaskDescription.get();
}

const TaskId& jsdk::Task::getGroupId() const
{
    return m_TaskGroupId;
}

bool jsdk::Task::isInGroup() const
{
    return m_TaskGroupId.isValid();
}

const TaskId & jsdk::Task::getTaskId() const
{
    return m_TaskId;
}

void jsdk::Task::setTaskId(const TaskId & taskId)
{
    m_time.start();
    m_TaskId = taskId;
}

void jsdk::Task::setTaskGroupId(const TaskId & taskGroupId)
{
    m_TaskGroupId = taskGroupId;
}

bool jsdk::Task::exctue()
{
    TaskManager& taskManager = TaskManager::get();
    DBG_WARN_AND_RETURN_FALSE_UNLESS(m_opTaskDescription, L"任务描述无效", L"蒋家伟", L"2023-08-02");
    OwnerPtr<ITaskExectutable>  opTaskExectutable = taskManager.getTaskExectutable(*m_opTaskDescription);
    std::wstring description = m_opTaskDescription->getDescription();
    DBG_WARN_AND_RETURN_FALSE_UNLESS(opTaskExectutable, L"< " + description + L" >没有注册执行者", L"蒋家伟", L"2023-08-02");
    int currentTime = m_time.elapsed();
    DBG_WARN(L"< " + description + L" >任务, id ：" + StringUtils::toWString(m_TaskId.toValue()) + L" 开始执行" + L"; 期望延迟时间 : "+ StringUtils::toWString(m_delayTime) + L"ms, 实际延迟时间 ：" + StringUtils::toWString(currentTime) + L" ms", L"蒋家伟", L"2023-08-28");
    bool success = opTaskExectutable->On(std::move(m_opTaskDescription));
    DBG_WARN(L"< " + description + L" >任务, id : " + StringUtils::toWString(m_TaskId.toValue()) + L" 执行" + (success ? L"成功" : L"失败") + L"; 实际消耗时间 ：" + StringUtils::toWString(m_time.elapsed() - currentTime) + L" ms", L"蒋家伟", L"2023-08-28");
    return success;
}

bool jsdk::Task::hasDelayTime() const
{
    return m_delayTime > 0;
}

void jsdk::Task::startTimer() const
{
    TaskId taskId = m_TaskId;
    if (m_delayTime == 0)
    {
        DBG_WARN(L"此任务由于时间补偿导致了延迟为0, 实际延时大于等于原延迟", L"蒋家伟", L"2023-10-30");
        TaskEventArgs args(TaskEventType::DelayTaskTrigger, taskId);
        TaskEvent::get().sendEvent(&args);
    }
    else
    {
        QTimer::singleShot(m_delayTime, [taskId]() {
            TaskEventArgs args(TaskEventType::DelayTaskTrigger, taskId);
            TaskEvent::get().sendEvent(&args);
        });
    }
}

jsdk::Task::Task(OwnerPtr<ITaskDescription> opTaskDescription, uint32_t delayTime):
    m_opTaskDescription(std::move(opTaskDescription)),
    m_delayTime(delayTime)
{
    DBG_WARN_UNLESS(delayTime < 20000, L"任务延迟时间不应该太长", L"蒋家伟", L"2023-08-17");
}